package com.cci.kangdao.dao;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.mybatis.spring.annotation.MapperScan;

import java.util.List;
import java.util.Map;

@MapperScan
public interface BusinessRegionTDao {

	//根据用户id获取管辖下所有区域信息
	@Select("select b.ID as RegionId,b.RegionNo,b.RegionName from BusinessRegionUserRelation_T a \n" +
			"inner join BusinessRegion_T b on a.RegionId = b.ID\n" +
			"where a.Flag = 0 and UserId = #{userId} and b.Flag = 0")
	List<Map<String,Object>> getRegionListByUserId(@Param("userId") long userId);

	//根据父区域主键id获取管辖下所有子(一级)区域信息    作用：转化为一级区域
	@Select("select distinct tt.* from (\n" +
			"select a.* from BusinessRegion_T a\n" +
			"where a.ID = #{regionId} and a.Level = 1 and a.Flag = 0\n" +
			"union all\n" +
			"select * from BusinessRegion_T a\n" +
			"where a.ID in (select a.SubRegionId from BusinessRegionRelation_T a\n" +
			"where a.RegionId = #{regionId} and a.Flag = 0) and a.Level = 1 and a.Flag = 0\n" +
			"union all\n" +
			"select * from BusinessRegion_T a\n" +
			"where a.ID in(select a.SubRegionId from BusinessRegionRelation_T a\n" +
			"where a.Flag = 0 and a.RegionId in(select a.SubRegionId from BusinessRegionRelation_T a\n" +
			"where a.RegionId = #{regionId} and a.Flag = 0)) and a.Level = 1 and a.Flag = 0\n" +
			") as tt ")
	List<Map<String,Object>> getLevelOneRegionListByParentRegionId(@Param("regionId") long regionId);

	//根据区域id(多个区域id  字符串类型)获取管辖下所有经销商id(多个经销商id   字符串类型)
    @Select("<script>select distinct g.ServiceStationID from BusinessRegion_T a\n" +
            "inner join BusinessRegionLabelRelation_T b on a.ID = b.RegionId\n" +
            "inner join Position_T c on a.SubRegionNo = c.CrmPostNo\n" +
            "inner join PositionUser_T d on c.ID = d.PositionID\n" +
            "inner join PositionUserServiceStation_T g on d.ID = g.PositionUserID \n" +
            "inner join BusinessStationLabelRelation_T h on g.ServiceStationID = h.ServiceStationId and b.LabelId = h.LabelId\n" +
            "where a.Flag = 0 and a.ID in <foreach collection='levenOneRegionStr' item='item' open='(' separator=',' close=')'>#{item} </foreach> and b.Flag = 0 and c.Flag = 0 and d.Flag = 0 and g.Flag = 0 and h.Flag = 0 </script>")
    List<String> getServiceStationIdListByLevelOneRegionList(@Param("levenOneRegionStr") List<String> levenOneRegionStr);
}
